package com.wclass.controller.app;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wclass.common.ReturnObject;
import com.wclass.common.ToolUtil;
import com.wclass.entity.*;
import com.wclass.interceptor.BaseContextHandler;
import com.wclass.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Api(description = "机构/团队管理")
@RestController
@RequestMapping("/organ")
public class OrganController {
    @Autowired
    private IBaseOrganService iBaseOrganService;
    @Autowired
    private ICourseInfoService iCourseInfoService;
    @Autowired
    private IBaseOrganStuService iBaseOrganStuService;
    @Autowired
    private IBaseAppUserService iBaseAppUserService;
    @Autowired
    private IBaseTeamPicService iBaseTeamPicService;
    @Autowired
    private IBaseTeamDevelopHistoryService iBaseTeamDevelopHistoryService;
    @Autowired
    private IBaseTeamCourseIntroService iBaseTeamCourseIntroService;
    @Autowired
    private IBaseTeamUserService iBaseTeamUserService;
    @Autowired
    private IBaseNoticeService iBaseNoticeService;
    @Autowired
    private IBaseFeedbackService iBaseFeedbackService;
    @Autowired
    private IBaseFocusService iBaseFocusService;
    @Autowired
    private IBaseIdService iBaseIdService;

    @ApiOperation("获取机构详情信息")
    @RequestMapping(value = "/getOrganInfo", method = RequestMethod.POST)
    public ReturnObject<BaseOrgan> getOrganInfo(@ApiParam("机构/团队id") @RequestParam Long id) {
        BaseOrgan organ = iBaseOrganService.selectById(id);
        return new ReturnObject<>(0, "获取成功", organ);
    }

    @ApiOperation("获取机构课程分页")
    @RequestMapping(value = "/getCoursePageByOrganId", method = RequestMethod.POST)
    public ReturnObject<List<CourseInfo>> getCoursePageByOrganId(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                                 @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                                 @ApiParam("机构/团队id") @RequestParam Long organId,
                                                                 @ApiParam("等级 1 零基础 2 进阶") Integer level,
                                                                 @ApiParam("课程价格类型，1：免费，2：收费") Integer priceType) {

        EntityWrapper<CourseInfo> ew = new EntityWrapper<>();
        ew.eq("baseAppUser.institution_id", organId);
        if (level != null) {
            //机构主页下的普通课程、重点课程列表
            ew.eq("info.level", level);
        } else {
            //机构全部课程筛选页面
            if (priceType != null && priceType == 1)
                ew.eq("info.amount", 0);
            else if (priceType != null && priceType == 2)
                ew.gt("info.amount", 0);
            ew.orderBy("info.live_type", true).orderBy("info.amount", true).orderBy("info.star", false);
        }
        Page<CourseInfo> obj = iCourseInfoService.selectPage(new Page<>(offset, limit), ew);

        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }

    @ApiOperation("获取机构教师团队")
    @RequestMapping(value = "/getTeaListUnderOrgan", method = RequestMethod.POST)
    public ReturnObject<List<BaseAppUser>> getTeaListUnderOrgan(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                          @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                          @ApiParam("机构/团队id") @RequestParam Long organId){
        EntityWrapper<BaseAppUser> ew = new EntityWrapper<>();
        ew.eq("institution_id", organId);
        Page<BaseAppUser> obj = iBaseAppUserService.selectPage(new Page<>(offset, limit), ew);

        for (int i = 0;i < obj.getRecords().size();i++) {
            BaseAppUser appUser = obj.getRecords().get(i);
            int count = iBaseFocusService.selectCount(
                    new EntityWrapper<BaseFocus>().eq("user_id", BaseContextHandler.getUserID()).eq("focus_user_id", appUser.getId()).eq("state", 0));
            appUser.setIsFocus(count);
        }

        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }

    @ApiOperation("机构-认证中心-修改/新增机构认证信息")
    @RequestMapping(value = "/saveOrganInfo", method = RequestMethod.POST)
    public ReturnObject<BaseOrgan> saveOrganInfo(@ApiParam("机构id") Long organId,
                                                 @ApiParam("机构图标") String institutionLogo,
                                                 @ApiParam("机构名称") String name,
                                                 @ApiParam("教学领域") String teachingDomain,
                                                 @ApiParam("机构简介") String institutionIntro,
                                                 @ApiParam("联系人") String institutionBelong,
                                                 @ApiParam("电话") String phone,
                                                 @ApiParam("邮箱") String email,
                                                 @ApiParam("公司全称") String companyName,
                                                 @ApiParam("创建时间（yyyy-MM-dd）") @DateTimeFormat(pattern = "yyyy-MM-dd") Date companyCrtTime,
                                                 @ApiParam("运营时长") String companyOperation,
                                                 @ApiParam("公司简介") String companyIntro,
                                                 @ApiParam("公司环境") String companyEnvironment,
                                                 @ApiParam("财务表报") String companyFinance,
                                                 @ApiParam("特色课程") String companyCourse,
                                                 @ApiParam("营业代码") String institutionCode,
                                                 @ApiParam("营业执照") String institutionLicense,
                                                 @ApiParam("在线授课案例") String companyCase,
                                                 @ApiParam("新浪微博") String sina,
                                                 @ApiParam("微信公众号") String weixin,
                                                 @ApiParam("其他平台") String terrace,
                                                 @ApiParam("收款账户") String collectionAccount,
                                                 @ApiParam("开户号") String openingBank,
                                                 @ApiParam("开户证明") String openingProve) {
        BaseOrgan baseOrgan = iBaseOrganService.selectById(organId);

        if (baseOrgan != null) {
            baseOrgan.setAuditStatus(0);
            baseOrgan.setInstitutionLogo(institutionLogo);
            baseOrgan.setName(name);
            baseOrgan.setTeachingDomain(teachingDomain);
            baseOrgan.setInstitutionIntro(institutionIntro);
            baseOrgan.setInstitutionBelong(institutionBelong);
            baseOrgan.setPhone(phone);
            baseOrgan.setEmail(email);
            baseOrgan.setCompanyName(companyName);
            baseOrgan.setCompanyCrtTime(companyCrtTime);
            baseOrgan.setCompanyOperation(companyOperation);
            baseOrgan.setCompanyIntro(companyIntro);
            baseOrgan.setCompanyEnvironment(companyEnvironment);
            baseOrgan.setInstitutionCode(institutionCode);
            baseOrgan.setInstitutionLicense(institutionLicense);
            baseOrgan.setCompanyFinance(companyFinance);
            baseOrgan.setCompanyCourse(companyCourse);
            baseOrgan.setCompanyCase(companyCase);
            baseOrgan.setSina(sina);
            baseOrgan.setWeixin(weixin);
            baseOrgan.setTerrace(terrace);
            baseOrgan.setCollectionAccount(collectionAccount);
            baseOrgan.setOpeningBank(openingBank);
            baseOrgan.setOpeningProve(openingProve);
            iBaseOrganService.updateById(baseOrgan);
        } else {
            BaseId baseId = iBaseIdService.getNoUseId(3);

            baseOrgan = new BaseOrgan();
            baseOrgan.setId(Long.parseLong(baseId.getId() + ""));
            baseOrgan.setUserId(BaseContextHandler.getUserID());
            baseOrgan.setCrtTime(new Date());
            baseOrgan.setInstitutionLogo(institutionLogo);
            baseOrgan.setName(name);
            baseOrgan.setTeachingDomain(teachingDomain);
            baseOrgan.setInstitutionIntro(institutionIntro);
            baseOrgan.setInstitutionBelong(institutionBelong);
            baseOrgan.setPhone(phone);
            baseOrgan.setEmail(email);
            baseOrgan.setType(1);
            baseOrgan.setCompanyName(companyName);
            baseOrgan.setCompanyCrtTime(companyCrtTime);
            baseOrgan.setCompanyOperation(companyOperation);
            baseOrgan.setCompanyIntro(companyIntro);
            baseOrgan.setCompanyEnvironment(companyEnvironment);
            baseOrgan.setInstitutionCode(institutionCode);
            baseOrgan.setInstitutionLicense(institutionLicense);
            baseOrgan.setCompanyFinance(companyFinance);
            baseOrgan.setCompanyCourse(companyCourse);
            baseOrgan.setCompanyCase(companyCase);
            baseOrgan.setSina(sina);
            baseOrgan.setWeixin(weixin);
            baseOrgan.setTerrace(terrace);
            baseOrgan.setCollectionAccount(collectionAccount);
            baseOrgan.setOpeningBank(openingBank);
            baseOrgan.setOpeningProve(openingProve);
            iBaseOrganService.insert(baseOrgan);

            baseId.setOrganState(1);
            iBaseIdService.updateById(baseId);

            BaseAppUser appUser = iBaseAppUserService.selectById(BaseContextHandler.getUserID());
            appUser.setRoldId(1);
            appUser.setInstitutionId(baseOrgan.getId());
            appUser.setInstitutionInviteState(2);
            iBaseAppUserService.updateById(appUser);
        }

        return new ReturnObject<>(0, "请求成功", baseOrgan);
    }


    @ApiOperation("机构-认证中心-新增优秀学员展示")
    @RequestMapping(value = "/addOrganStuInfo", method = RequestMethod.POST)
    public ReturnObject<BaseOrgan> addOrganStuInfo(@ApiParam("机构id") @RequestParam Long organId,
                                                   @ApiParam("学员姓名") String name,
                                                   @ApiParam("学员电话") String phone,
                                                   @ApiParam("培训课程") String course,
                                                   @ApiParam("获取成果") String achievement) {
        BaseOrgan baseOrgan = iBaseOrganService.selectById(organId);
        if (baseOrgan != null) {
            BaseOrganStu organStu = new BaseOrganStu();
            organStu.setState(0);
            organStu.setCrtTime(new Date());
            organStu.setOrganId(organId);
            organStu.setName(name);
            organStu.setPhone(phone);
            organStu.setCourse(course);
            organStu.setAchievement(achievement);
            iBaseOrganStuService.insert(organStu);
        }

        return new ReturnObject<>(0, "请求成功");
    }

    @ApiOperation("机构-认证中心-批量新增优秀学员展示")
    @RequestMapping(value = "/addBatchOrganStuInfo", method = RequestMethod.POST)
    public ReturnObject addBatchOrganStuInfo(@ApiParam("机构id") @RequestParam Long organId,
                                             @ApiParam("学生JSON") String stuInfo){
        BaseOrgan baseOrgan = iBaseOrganService.selectById(organId);

        if (baseOrgan != null) {
            JSONArray arr = JSON.parseArray(stuInfo);
            List<BaseOrganStu> list = Lists.newArrayList();
            for (int i = 0;i < arr.size();i++) {
                JSONObject obj = arr.getJSONObject(i);

                BaseOrganStu organStu = new BaseOrganStu();
                organStu.setState(0);
                organStu.setCrtTime(new Date());
                organStu.setOrganId(organId);
                organStu.setName(obj.getString("name"));
                organStu.setPhone(obj.getString("phone"));
                organStu.setCourse(obj.getString("course"));
                organStu.setAchievement(obj.getString("achievement"));
                list.add(organStu);
            }
            if (list.size() > 0)
                iBaseOrganStuService.insertBatch(list);
        }

        return new ReturnObject<>(0, "请求成功");
    }

    @ApiOperation("机构-认证中心-优秀学员分页")
    @RequestMapping(value = "/getOrganStuPageByOrganId", method = RequestMethod.POST)
    public ReturnObject<List<BaseOrganStu>> getOrganStuPageByOrganId(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                                     @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                                     @ApiParam("机构/团队id") @RequestParam Long organId) {

        EntityWrapper<BaseOrganStu> ew = new EntityWrapper<>();
        ew.orderBy("crt_time");
        ew.eq("organ_id", organId).eq("state", 0);
        Page<BaseOrganStu> obj = iBaseOrganStuService.selectPage(new Page<>(offset, limit), ew);

        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }

    @ApiOperation("机构-认证中心-删除优秀学员")
    @RequestMapping(value = "/delOrganStuInfo", method = RequestMethod.POST)
    public ReturnObject<Object> addOrganStuInfo(@ApiParam("id") @RequestParam Long id) {
        BaseOrganStu info = iBaseOrganStuService.selectById(id);
        info.setState(1);
        iBaseOrganStuService.updateById(info);
        return new ReturnObject<>(0, "删除成功");
    }

    @ApiOperation("举报机构、团队")
    @RequestMapping(value = "/reportOrgan", method = RequestMethod.POST)
    public ReturnObject reportOrgan(@ApiParam("机构、团队id") @RequestParam Long id,
                                    @ApiParam("举报内容") @RequestParam String content){
        //插入举报记录
        BaseFeedback feedback = new BaseFeedback();
        feedback.setCrtTime(new Date());
        feedback.setState(0);
        feedback.setContent(content);
        feedback.setPhone(iBaseAppUserService.selectById(BaseContextHandler.getUserID()).getPhone());
        feedback.setType(4);
        feedback.setReportId(id);
        feedback.setUserId(BaseContextHandler.getUserID());
        iBaseFeedbackService.insert(feedback);
        return new ReturnObject(0, "操作成功");
    }

    @ApiOperation("团队-获取团队主页信息")
    @RequestMapping(value = "/getTeamHomeInfo", method = RequestMethod.POST)
    public ReturnObject<BaseOrgan> getTeamHomeInfo(){
        BaseAppUser appUser = iBaseAppUserService.selectById(BaseContextHandler.getUserID());
        BaseOrgan team = iBaseOrganService.selectOne(new EntityWrapper<BaseOrgan>().eq("user_id", appUser.getId()).eq("type", 2));
        if (team == null) {
            return new ReturnObject(-1, "未创建团队，无团队信息");
        }
        if (appUser.getRoldId() > 2) {
            return new ReturnObject(-1, "没有编辑团队主页信息权限");
        }
        List<BaseTeamPic> teamPicList = iBaseTeamPicService.selectList(new EntityWrapper<BaseTeamPic>().eq("team_id", team.getId()));
        team.setTeamPicList(teamPicList);

        List<BaseTeamDevelopHistory> teamDevelopHistoryList = iBaseTeamDevelopHistoryService.selectList(new EntityWrapper<BaseTeamDevelopHistory>().eq("team_id", team.getId()));
        team.setTeamDevelopHistoryList(teamDevelopHistoryList);

        List<BaseTeamCourseIntro> teamCourseIntroList = iBaseTeamCourseIntroService.selectList(new EntityWrapper<BaseTeamCourseIntro>().eq("team_id", team.getId()));
        team.setTeamCourseIntroList(teamCourseIntroList);

        List<BaseTeamUser> teamUserList = iBaseTeamUserService.selectList(new EntityWrapper<BaseTeamUser>().eq("team_id", team.getId()));
        team.setTeamUserList(teamUserList);

        return new ReturnObject(0, "获取成功", team);
    }

    @ApiOperation("团队-新增、编辑团队主页")
    @RequestMapping(value = "/saveTeamHomePage", method = RequestMethod.POST)
    public ReturnObject saveTeamHomePage(@ApiParam("团队id") Long teamId,
                                         @ApiParam("团队简介") String teamIntro,
                                         @ApiParam("简介图片") String introPic,
                                         @ApiParam("宣传图片list") String teamPicList,
                                         @ApiParam("发展历程list") String teamDevelopHistoryList,
                                         @ApiParam("课程合辑list") String teamCourseIntroList,
                                         @ApiParam("教师团队list") String teamUserList){
        //保存团队基本信息
        BaseId baseId = iBaseIdService.getNoUseId(3);

        BaseOrgan team = new BaseOrgan();
        team.setState(0);
        team.setTeamIntro(teamIntro);
        team.setTeamIntroPic(introPic);
        team.setUserId(BaseContextHandler.getUserID());
        if (teamId == null) {
            team.setId(Long.parseLong(baseId.getId() + ""));
            team.setCrtTime(new Date());
            team.setType(2);
            iBaseOrganService.insert(team);

            baseId.setOrganState(1);
            iBaseIdService.updateById(baseId);
        } else {
            team.setId(teamId);
            iBaseOrganService.updateById(team);
        }
        //保存宣传图片
        JSONArray teamPicArr = JSONArray.parseArray(teamPicList);
        List<BaseTeamPic> teamPics = Lists.newArrayList();
        for (int i = 0;i < teamPicArr.size();i++) {
            BaseTeamPic teamPic = JSONObject.parseObject(JSONObject.toJSONString(teamPicArr.get(i)), BaseTeamPic.class);
            teamPic.setTeamId(team.getId());
            if (teamPic.getId() == null)
                teamPic.setCrtTime(new Date());
            teamPics.add(teamPic);
        }
        if (teamPics.size() > 0)
            iBaseTeamPicService.insertOrUpdateBatch(teamPics);

        //保存发展历程
        JSONArray teamDevelopHistoryArr = JSONArray.parseArray(teamDevelopHistoryList);
        List<BaseTeamDevelopHistory> teamDevelopHistorys = Lists.newArrayList();
        for (int i = 0;i < teamDevelopHistoryArr.size();i++) {
            BaseTeamDevelopHistory teamDevelopHistory = JSONObject.parseObject(JSONObject.toJSONString(teamDevelopHistoryArr.get(i)), BaseTeamDevelopHistory.class);
            teamDevelopHistory.setTeamId(team.getId());
            if (teamDevelopHistory.getId() == null)
                teamDevelopHistory.setCrtTime(new Date());
            teamDevelopHistorys.add(teamDevelopHistory);
        }
        if (teamDevelopHistorys.size() > 0)
            iBaseTeamDevelopHistoryService.insertOrUpdateBatch(teamDevelopHistorys);

        //保存团队课程
        JSONArray teamCourseIntroArr = JSONArray.parseArray(teamCourseIntroList);
        List<BaseTeamCourseIntro> teamCourseIntros = Lists.newArrayList();
        for (int i = 0;i < teamCourseIntroArr.size();i++) {
            BaseTeamCourseIntro teamCourseIntro = JSONObject.parseObject(JSONObject.toJSONString(teamCourseIntroArr.get(i)), BaseTeamCourseIntro.class);
            teamCourseIntro.setTeamId(team.getId());
            if (teamCourseIntro.getId() == null)
                teamCourseIntro.setCrtTime(new Date());
            teamCourseIntros.add(teamCourseIntro);
        }
        if (teamCourseIntros.size() > 0)
            iBaseTeamCourseIntroService.insertOrUpdateBatch(teamCourseIntros);

        //保存教师团队
        JSONArray teamUserArr = JSONArray.parseArray(teamUserList);
        List<BaseTeamUser> teamUsers = Lists.newArrayList();
        for (int i = 0;i < teamUserArr.size();i++) {
            BaseTeamUser teamUser = JSONObject.parseObject(JSONObject.toJSONString(teamUserArr.get(i)), BaseTeamUser.class);
            if (teamUser.getId() == null) {
                teamUser.setTeamId(team.getId());
                teamUser.setShowType(1);
                teamUser.setCrtTime(new Date());
            }
            teamUsers.add(teamUser);
        }
        if (teamUsers.size() > 0)
            iBaseTeamUserService.insertOrUpdateBatch(teamUsers);

        return new ReturnObject(0, "操作成功");
    }

    @ApiOperation("获取成员管理")
    @RequestMapping(value = "/getMemberList", method = RequestMethod.POST)
    public ReturnObject<List<BaseAppUser>> getMemberList(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                         @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                         @ApiParam("邀请状态，全部不传，1：等待通过邀请，2：已添加，3：已拒绝") Integer institutionInviteState,
                                                         @ApiParam("搜索关键字") String searchWord){
        BaseAppUser appUser = iBaseAppUserService.selectById(BaseContextHandler.getUserID());
        if (appUser.getRoldId() == null) {
            return new ReturnObject<>(-1, "机构、团队内担任职务角色无成员管理权限");
        }
        if (appUser.getInstitutionId() != null && appUser.getRoldId() > 2 && appUser.getInstitutionInviteState() == 2) {
            return new ReturnObject<>(-1, "机构、团队内担任职务角色无成员管理权限");
        } else if (appUser.getInstitutionId() != null && appUser.getInstitutionInviteState() == 1) {
            return new ReturnObject<>(-1, "有机构、团队未回应的加入邀请");
        } else if ((appUser.getInstitutionId() != null && appUser.getInstitutionInviteState() == 3)
                || appUser.getInstitutionId() == null) {
            return new ReturnObject<>(0, "获取成功", 0, 0, Lists.newArrayList());
        }

        Page<BaseAppUser> obj;
        //机构校长、团队创始人
        EntityWrapper<BaseAppUser> ew = new EntityWrapper<>();
        if (StringUtils.isNotBlank(searchWord))
            ew.like("nick_name", searchWord).or().like("id", searchWord).andNew();
        if (institutionInviteState != null)
            ew.eq("institution_invite_state", institutionInviteState);
        ew.eq("institution_id", appUser.getInstitutionId());
        obj = iBaseAppUserService.selectPage(new Page<>(offset, limit), ew);

        for (BaseAppUser user : obj.getRecords()) {
            user.setPassword(null);
        }

        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }

    @ApiOperation("获取成员信息")
    @RequestMapping(value = "/getMemberUserInfo", method = RequestMethod.POST)
    public ReturnObject<Map<String, Object>> getMemberUserInfo(@ApiParam("成员id") @RequestParam Long userId){
        Map<String, Object> map = Maps.newHashMap();

        BaseAppUser appUser = iBaseAppUserService.selectById(userId);
        map.put("userId", userId);
        map.put("pictureAddress", appUser.getPictureAddress());
        map.put("nickName", appUser.getNickName());
        map.put("institutionInviteState", appUser.getInstitutionInviteState());

        List<CourseInfo> list = iCourseInfoService.selectList(new EntityWrapper<CourseInfo>().eq("user_id", userId));
        JSONArray courseNameArray = new JSONArray();
        for (CourseInfo courseInfo : list) {
            courseNameArray.add(courseInfo.getName());
        }
        map.put("courseNameArr", courseNameArray);

        return new ReturnObject<>(0, "获取成功", map);
    }

    @ApiOperation("获取成员编辑信息")
    @RequestMapping(value = "/getMemberInfoForEdit", method = RequestMethod.POST)
    public ReturnObject<BaseTeamUser> getMemberInfoForEdit(@ApiParam("成员id") @RequestParam Long userId){
        BaseTeamUser teamUser = iBaseTeamUserService.selectOne(new EntityWrapper<BaseTeamUser>().eq("user_id", userId));
        teamUser.setPositionName(ToolUtil.getRoleName(teamUser.getPosition()));

        BaseAppUser appUser = iBaseAppUserService.selectById(userId);
        teamUser.setPicUrl(appUser.getPictureAddress());
        teamUser.setName(appUser.getNickName());
        teamUser.setPhone(appUser.getPhone());
        teamUser.setIntro(appUser.getPersonalIntro());
        return new ReturnObject<>(0, "获取成功", teamUser);
    }

    @ApiOperation("编辑保存成员信息")
    @RequestMapping(value = "/editMemberInfo", method = RequestMethod.POST)
    public ReturnObject editMemberInfo(@ApiParam("成员用户id") @RequestParam Long userId,
                                       @ApiParam("头像图片地址") @RequestParam String picUrl,
                                       @ApiParam("姓名") @RequestParam String name,
                                       @ApiParam("电话") @RequestParam String phone,
                                       @ApiParam("简介") @RequestParam String intro){
        BaseAppUser appUser = iBaseAppUserService.selectById(userId);
        appUser.setNickName(name);
        appUser.setPictureAddress(picUrl);
        appUser.setPhone(phone);
        appUser.setPersonalIntro(intro);
        iBaseAppUserService.updateById(appUser);
        return new ReturnObject(0, "修改成功");
    }

    @ApiOperation("移除成员")
    @RequestMapping(value = "/removeMember", method = RequestMethod.POST)
    public ReturnObject<List<CourseInfo>> removeMember(@ApiParam("成员id") @RequestParam Long userId){
        BaseAppUser appUser = iBaseAppUserService.selectById(userId);

        if (appUser.getRoldId() == 1) {
            return new ReturnObject<>(-1, "校长不能移除");
        }
        BaseAppUser loginUser = iBaseAppUserService.selectById(BaseContextHandler.getUserID());
        if (loginUser.getRoldId() == 2 && appUser.getRoldId() == 2) {
            return new ReturnObject<>(-1, "教务主任不能移除教务主任");
        }

        //判断成员是否有机构、团队直播课程未完结
        BaseOrgan organ = iBaseOrganService.selectById(appUser.getInstitutionId());
        EntityWrapper<CourseInfo> ew = new EntityWrapper<>();
        ew.eq("user_id", userId);
        ew.eq("live_type", 0);
        ew.eq("crt_user_id", organ.getUserId());
        ew.lt("end_time", new Date());
        List<CourseInfo> list = iCourseInfoService.selectList(ew);
        if (list.size() > 0) {
            return new ReturnObject<>(-1,
                    appUser.getNickName() + "（" + userId + "）成员，当前与" + list.size() + "门未完结课程有关联，请先解除关联关系（教务主任、老师、助教、销售、财务）", list);
        }

        //删除机构、团队成员记录
        iBaseTeamUserService.delete(new EntityWrapper<BaseTeamUser>().eq("user_id", userId));

        //修改用户绑定机构状态，置为null
        iBaseAppUserService.updateUserOrganBind(userId);

        return new ReturnObject<>(0, "移除成功");
    }

    @ApiOperation("获取身份成员数")
    @RequestMapping(value = "/getOrganRoleCount", method = RequestMethod.POST)
    public ReturnObject<List<Map<String, Object>>> getOrganRoleCount(@ApiParam("机构、团队id") @RequestParam Long organId){
        EntityWrapper<BaseAppUser> ew;
        List<Map<String, Object>> list = Lists.newArrayList();

        for (int i = 1;i <= 6;i++) {
            Map<String, Object> ret = Maps.newHashMap();
            ret.put("roleId", i);
            ew = new EntityWrapper<>();
            ew.eq("institution_id", organId).eq("rold_id", i);
            int num = iBaseAppUserService.selectCount(ew);
            ret.put("num", num);
            ret.put("institutionId", organId);
            ret.put("roleName", ToolUtil.getRoleName(i));
            ret.put("roleRemark", ToolUtil.getRoleRemark(i));
            list.add(ret);
        }

        return new ReturnObject<>(0, "获取成功", list);
    }

    @ApiOperation("获取身份下成员列表")
    @RequestMapping(value = "/getMemberListByRole", method = RequestMethod.POST)
    public ReturnObject<List<BaseAppUser>> getMemberListByRole(@ApiParam("机构id") @RequestParam Long organId,
                                                               @ApiParam("身份角色类型") @RequestParam Integer roleType){
        EntityWrapper<BaseAppUser> ew = new EntityWrapper<>();
        ew.setSqlSelect("id,nick_name,course_num");
        ew.eq("institution_invite_state", 2);
        ew.eq("institution_id", organId);
        ew.eq("rold_id", roleType);
        List<BaseAppUser> list = iBaseAppUserService.selectList(ew);

        return new ReturnObject<>(0, "获取成功", list);
    }

    @ApiOperation("设置身份-搜索老师列表")
    @RequestMapping(value = "/searchTeaForAdd", method = RequestMethod.POST)
    public ReturnObject<List<BaseAppUser>> searchTeaForAdd(@ApiParam("搜索关键字") String searchWord,
                                                           @ApiParam("机构id") @RequestParam Long organId,
                                                           @ApiParam("身份角色类型") @RequestParam Integer roleType){
        //搜索机构、团队下接受邀请的老师
        EntityWrapper<BaseAppUser> ew = new EntityWrapper<>();
        ew.setSqlSelect("id,nick_name");
        ew.like("nick_name", searchWord).or().like("id", searchWord).andNew();
        //不是校长、创始人和需要添加的职务
        ew.notIn("rold_id", roleType + ",1").or().isNull("rold_id").andNew();
        ew.eq("institution_id", organId);
        ew.eq("institution_invite_state", 2);
        List<BaseAppUser> list = iBaseAppUserService.selectList(ew);

        return new ReturnObject(0, "获取成功", list);
    }

    @ApiOperation("设置成员身份")
    @RequestMapping(value = "/setTeaRole", method = RequestMethod.POST)
    public ReturnObject setTeaRole(@ApiParam("成员ids") @RequestParam String userIds,
                                   @ApiParam("身份角色类型") @RequestParam Integer roleType){
        if (roleType == 1) {
            return new ReturnObject(-1, "校长职务不能设置");
        }
        if (roleType == 2) {
            BaseAppUser loginUser = iBaseAppUserService.selectById(BaseContextHandler.getUserID());
            if (loginUser.getRoldId() == 2) {
                return new ReturnObject(-1, "不能设置教务主任职务");
            }
            int count = iBaseAppUserService.selectCount(new EntityWrapper<BaseAppUser>().eq("rold_id", 2).eq("institution_id", loginUser.getInstitutionId()));
            if (count > 0) {
                return new ReturnObject(-1, "只能有一个教务主任职务人员");
            }
        }
        //成员职务类型修改
        List<BaseAppUser> appUserList = iBaseAppUserService.selectBatchIds(Arrays.asList(userIds.split(",")));
        for (BaseAppUser appUser : appUserList) {
            appUser.setRoldId(roleType);

            BaseTeamUser teamUser = iBaseTeamUserService.selectOne(new EntityWrapper<BaseTeamUser>().eq("user_id", appUser.getId()));
            teamUser.setPosition(roleType);
            iBaseTeamUserService.updateById(teamUser);
        }
        iBaseAppUserService.updateBatchById(appUserList);

        return new ReturnObject(0, "设置成功");
    }

    @ApiOperation("邀请成员")
    @RequestMapping(value = "/addMember", method = RequestMethod.POST)
    public ReturnObject addMember(@ApiParam("被邀请人id") Long userId,
                                  @ApiParam("被邀请人手机号码") String phone){
        BaseAppUser loginUser = iBaseAppUserService.selectById(BaseContextHandler.getUserID());
        Long organId = loginUser.getInstitutionId();

        BaseAppUser appUser;
        if (userId != null) {
            appUser = iBaseAppUserService.selectById(userId);
        } else {
            appUser = iBaseAppUserService.selectOne(new EntityWrapper<BaseAppUser>().eq("phone", phone));
        }
        if (appUser == null) {
            return new ReturnObject(-1, "用户不存在");
        }
        if (appUser.getType() == 1) {
            return new ReturnObject(-1, "用户已成为认证教师，不能邀请");
        }
        if (appUser.getInstitutionId() != null && appUser.getInstitutionId() != organId &&
                (appUser.getInstitutionInviteState() == 1 || appUser.getInstitutionInviteState() == 2)) {
            return new ReturnObject(-1, "用户已被其他机构、团队邀请或已成为其他机构、团队成员");
        }
        if (appUser.getInstitutionId() == organId && appUser.getInstitutionInviteState() == 3) {
            return new ReturnObject(-1, "用户已拒绝成为机构、团队成员");
        }
        if (appUser.getInstitutionId() == organId &&
                (appUser.getInstitutionInviteState() == 1 || appUser.getInstitutionInviteState() == 2)) {
            return new ReturnObject(-1, "已邀请用户成为机构、团队成员");
        }
        appUser.setInstitutionId(organId);
        appUser.setInstitutionInviteState(1);
        iBaseAppUserService.updateById(appUser);

        BaseOrgan userOrgan =  iBaseOrganService.selectById(organId);
        BaseNotice notice = new BaseNotice();
        notice.setCrtTime(new Date());
        notice.setType(4);
        if (userOrgan.getType() == 1) {
            notice.setTitle("邀请你加入" + userOrgan.getName());
            notice.setContent(loginUser.getNickName() + "老师邀请你加入" + userOrgan.getName() + "，请仔细阅读用户协议后确认加入。");
        } else {
            notice.setTitle("邀请你加入" + loginUser.getNickName() + "的团队");
            notice.setContent(loginUser.getNickName() + "老师邀请你加入他的团队，请仔细阅读用户协议后确认加入。");
        }
        notice.setState(0);
        notice.setFromUserId(loginUser.getId());
        notice.setToUserId(appUser.getId());
        notice.setMsgType(1);
        notice.setReplyState(0);
        iBaseNoticeService.insert(notice);

        return new ReturnObject(0, "邀请成功");
    }


}

